/**
 * 预约模块全局会话限流器（仅限本进程内生效）。
 * - 默认上限 defaultLimit 来自配置（如 proxy.max_concurrent_sessions）。
 * - 可在一次批量任务期间通过 setLimit(…) 临时提升/降低上限，结束后 setLimit(null) 恢复默认。
 */

let inUse = 0
const waiters: Array<() => void> = []
let defaultLimit = 0
let overrideLimit: number | null = null

export function setDefaultLimit(limit: number): void {
  const v = Number(limit)
  defaultLimit = Number.isFinite(v) ? Math.max(0, Math.floor(v)) : 0
}

export function setLimit(limit: number | null): void {
  if (limit == null) {
    overrideLimit = null
    return
  }
  const v = Number(limit)
  overrideLimit = Number.isFinite(v) ? Math.max(0, Math.floor(v)) : 0
}

function currentLimit(): number {
  return overrideLimit != null ? overrideLimit : defaultLimit
}

export async function acquire(): Promise<void> {
  const limit = currentLimit()
  if (limit <= 0 || inUse < limit) {
    inUse++
    return
  }
  await new Promise<void>(resolve => waiters.push(resolve))
  inUse++
}

export function release(): void {
  inUse = Math.max(0, inUse - 1)
  const next = waiters.shift()
  if (next)
    next()
}

export function getInUse(): number { return inUse }
export function getLimit(): number { return currentLimit() }
